<template>
  <div class="audiobox" ref="audiobox">
    <div id="vs"></div>
    <canvas id="audioCanvas"></canvas>
    <div v-html="chapter.content"></div>
  </div>
</template>

<script>

import Music from 'xgplayer-music'
export default {
    props: {
        width: 900,
        height: 100,
        cwidth: 900,
        cheight: 300,
        autoplay: true,
        loop: true,
        chapter: {
            type: Object,
            require: false,
            default: () => {
                return {}
            }
        }
    },
    data() {
        return {
            musicPlayer: null
        }
    },
    mounted() {

    },
    methods: {
        initMusicPlayer(source, config) {
            console.log('初始化播放器', config)
            this.destroy()
            this.$nextTick(() => {
                const playerConfig = {
                    id: 'vs',
                    url: [source],
                    volume: 1,
                    width: this.width,
                    height: this.height,
                    autoplay: this.autoplay,
                    loop: this.loop,
                    mode: "order", //mode-当前播放模式，'order' | 'random' | 'loop'
                    timeScale: 15, //歌曲快进或后退的时间间隔，单位为秒，默认15秒
                }
                if (config.disableProgress) {
                    playerConfig.disableProgress = true
                }
                this.musicPlayer = new Music(playerConfig)
                // this.musicPlayer.crossOrigin = "anonymous"
                let an = this.musicPlayer.analyze(document.querySelector('#audioCanvas'))
                an.mode = 'bars'
                an.size = 256
                an.style = {
                    bgColor: "#000000",
                    color: "#50deb2",
                };
                
                // console.log(this.$refs.audiobox.clientWidth)
                document.querySelector("#audioCanvas").width = this.cwidth || this.$refs.audiobox.clientWidth
                document.querySelector("#audioCanvas").height = this.cheight || 300
            })
        },
        // 播放
        play(source = {}, config) {
            this.initMusicPlayer(source, config)
        },
        // 销毁
        destroy() {
            if (this.musicPlayer) {
                this.musicPlayer.destroy(false) 
                this.musicPlayer = null
            }
        }
    }
}
</script>

<style>

</style>